package utilities;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.Sprite;

import model.MapData;

public class TileMap {
	public static final int GARDEN_MAP = 1;
	public static final int LOGIN_MAP = 0;
	public static final int QUEST_PET_MAP = 2;
	public static final int FIGHTING_MAP = 3;
	
	public static final int m_iHeightTile = 24;
	public static final int m_iWidthTile = 24;
	
	public static TileMap instance = new TileMap();
	public static FrameImage m_frameImg;
	
	public MapData m_gardenMap;

	public TileMap() {
		// TODO Auto-generated constructor stub
		m_frameImg = null;
		
		m_gardenMap = null;
	}
	
	public void paintMap(Graphics g, int left, int top){
		int i, j, temp, tempY;
		for(i = 0; i < m_gardenMap.m_iMapHeight; i++){
			temp = i * m_gardenMap.m_iMapWidth;
			tempY = m_iHeightTile * i;
			for(j = 0; j < m_gardenMap.m_iMapWidth; j++){
				m_frameImg.drawFrame(m_gardenMap.m_data[temp + j], left + m_iWidthTile * j, top + tempY, Sprite.TRANS_NONE, g);
			}
		}
	}
	
	public void paintMap(Graphics g, int left, int top, int w, int h){
		int i, j, temp, tempY;
		for(i = 0; i < h; i++){
			temp = i * m_gardenMap.m_iMapWidth;
			tempY = m_iHeightTile * i;
			for(j = 0; j < w; j++){
				m_frameImg.drawFrame(m_gardenMap.m_data[temp + j], left + m_iWidthTile * j, top + tempY, Sprite.TRANS_NONE, g);
			}
		}
	}
	
	private void loadTile(){
		if(m_frameImg == null){
			m_frameImg = new FrameImage(ImagePack.createImage(ImagePack.TILE_PNG), m_iWidthTile, m_iHeightTile);
		}
	}
	
	public void loadMap(int map){
		try{
			loadTile();
			
			switch(map){
			case GARDEN_MAP:
				InputStream is = this.getClass().getResourceAsStream("/map_play");
				
				m_gardenMap = new MapData();
				m_gardenMap.importData(is, 60, 15);
				break;
			case LOGIN_MAP:
				is = this.getClass().getResourceAsStream("/maplogin");				
				m_gardenMap = new MapData();
				m_gardenMap.importData(is, 10, 7);
				break;
			case QUEST_PET_MAP:
				is = this.getClass().getResourceAsStream("/map_questPet");				
				m_gardenMap = new MapData();
				m_gardenMap.importData(is, 27, 15);
				break;
			case FIGHTING_MAP:
				is = this.getClass().getResourceAsStream("/fighting_map");
				m_gardenMap = new MapData();
				m_gardenMap.importData(is, 10, 7);
				break;
			default:
				break;
			}
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
